昨天我們有先學習 Promise 的部分, 也有稍微提到 asynchronous 程式設計寫法。
我們一直在寫的 JavaScript 程序自然都是非同步的 (asynchronous)。因為 JavaScript 從 callback 漸漸演進到一些非同步 (asynchronous) 的解法。昨天也有見識到 callback hell 的可怕。
我們將函數作為 arguments (arguments 會包含所有放入 function 中的參數值) 傳遞給其他函數,這樣一旦我們知道發生了預期的事情, 我們就可以 稍後做 callback 的動作 。
Example:
let myBtn = qs("button:nth-child(1)");
while (!myBtn.clicked) {
  // twiddle our thumbs (等待...)
}
console.log('"Finally Been Clicked", starring Drew Barrymore');
let myBtn2 = qs("button:nth-child(2)");
while (!myBtn2.clicked) {
  // twiddle our thumbs (等待...)
}
console.log('"Click 2", never coming soon to a theater near you');
with Promises
function firstBtnClick() {
  return new Promise(function (resolve) {
    let myBtn = qs("button:nth-child(1)");
    myBtn.addEventListener("click", resolve);
  });
}
function nextBtnClick() {
  return new Promise(function (resolve) {
    let myBtn = qs("button:nth-child(2)");
    myBtn.addEventListener("click", resolve);
  });
}
firstBtnClick()
  .then(() => {
    console.log('"Finally Been Clicked", starring Drew Barrymore');
  })
  .then(nextBtnClick)
  .then(() => {
    console.log('"Click 2", never coming soon to a theater near you');
  });
with Promises + 一點語法糖 (Syntactic Sugar)
function firstBtnClick() {
  return new Promise(function (resolve) {
    let myBtn = qs("button:nth-child(1)");
    myBtn.addEventListener("click", resolve);
  });
}
function nextBtnClick() {
  return new Promise(function (resolve) {
    let myBtn = qs("button:nth-child(2)");
    myBtn.addEventListener("click", resolve);
  });
}
await firstBtnClick();
console.log('"Finally Been Clicked", starring Drew Barrymore');
await nextBtnClick();
console.log('"Click 2", never coming soon to a theater near you');
將函數的返回值包裝在 promise 中的 語法糖 **(Syntactic Sugar)**
來承諾 code 等待 事物返回。
async function sayHelloAsync(name) {
  return "Hello " + name;
}
console.log(sayHelloAsync("nobody")); // Promise <pending>
let message = await sayHelloAsync("nobody");
console.log(message); // "Hello nobody"
async 其實對函數做同樣的事情, 像是 then
await 是暫停程式的執行,直到 Promise 被完成 (fulfilled/resolved),然後返回 promise resolved value
.then/.catch vs async/wait
使用 .then/.catch 鏈接
let newPromise = someFunction();
newPromise.then(func1).then(func2).then(func3).catch(errHandler);
使用 async/await
try {
  let a = await someFunction();
  let b = await func1(a);
  let c = await func2(b);
  let d = await func3(c);
} catch (err) {
  errHandler(err);
}
**注意: 不要過度使用 await, 只在有 code 等待 (awaited) 時才在 function call 之前包含 await